package com.qlylkj.lbk.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.model.event.LiveEvent
import com.qlylkj.lbk.ui.user.login.LoginActivity
import com.forest.core.etx.startKtxActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel

/**
 *    author : duanguosen
 *    date   : 2019/11/25
 *    desc   :
 */
abstract class BaseFragment : Fragment(), CoroutineScope by MainScope() {

    /**
     * 是否第一次加载数据
     */
    private var isFirstLoad  = true

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(setLayoutId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        LiveEventBus.get(LiveEvent.NETWORK_CHANGE_KEY, Boolean::class.java)
            .observeSticky(this, Observer<Boolean> {
                it?.let {
                    PreferenceHelper.hasNetwork = it
                    checkNetwork()
                }
            })
        initView()

    }

    override fun onResume() {
        super.onResume()
        if(isFirstLoad ){
            initData()
            isFirstLoad = false
        }
    }

    protected fun toLogin() {
        startKtxActivity<LoginActivity>()
    }

    protected fun isLoginPrompt(): Boolean {
        if (!PreferenceHelper.isLogin) {
            toLogin()
        }
        return PreferenceHelper.isLogin
    }

    @LayoutRes
    protected abstract fun setLayoutId(): Int
    protected abstract fun initView()
    protected abstract fun initData()

    private fun checkNetwork() {
        if (PreferenceHelper.hasNetwork) {
            doReConnected()
        }else{
            doNotNetwork()
        }
    }

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {

    }

    open fun doNotNetwork(){

    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }
}